from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

from django.contrib.auth.hashers import make_password, check_password
from .. import models
from django.core.urlresolvers import reverse
from web.settings import BASE_DIR
import os
from . viewsindex import uploads
from django.contrib.auth.decorators import permission_required


@permission_required('myadmin.show_users',raise_exception = True)
# 后台用户列表
def userindex(request):
    # 获取所有的用户信息
    data = models.Users.objects.filter().exclude(status=3)

    # 获取搜索条件和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断搜索的类型
        if types == 'all':
            # 多字段的条件搜索
            # select * from users where username like '%a%' or phone like '%a%'...
            # filter(username=a,password=b) 等价于　filter(username=a).filter(password=b)
            # Q对象 进行复杂查找
            from django.db.models import Q
            data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords))
        elif types == 'status':
            arr = {'正常':0,'禁用':1,'删除':3}
            data = data.filter(status=arr[keywords])
        # elif types == 'sex':
            # arr = {'男':'1','女':'0'}
            # data = data.filter(sex=keywords)
        else:
        # elif types == 'username':
            # data = data.filter(username__contains=keywords)
            search = {types+'__contains':keywords}
            data = data.filter(**search)
    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类 参数1是获取的所有的数据对象，参数2是每页显示多少条
    paginator = Paginator(data,10)

    # 获取当前页的数据
    p = request.GET.get('p',1)
    # 获取当前页的数据
    userlist = paginator.page(p)
    # print(paginator.page_range)  结果 ：range(1, 17)


    # print(data)
    # print(userlist)
    # <QuerySet [<Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, <Users: Users object>, '...(remaining elements truncated)...']>
    # <Page 2 of 16>

    # 分配数据
    context = {'userlist':userlist}
    # 加载用户列表模板
    return render(request,'myadmin/users/index.html',context)


@permission_required('myadmin.insert_users',raise_exception = True)
# 后台会员管理的表单
def useradd(request):
    try:
        # 判断当前的请求方式
        if request.method == 'GET':
            # 加载表单页面
            return render(request,'myadmin/users/add.html')
        elif request.method == 'POST':
            # 接收数据,进行处理
            # print(request.POST) <QueryDict: {'age': ['１１１'], 'email': ['１１１１１'], 'username': ['问问'], 'sex': ['0'], 'pic_url': [''], 'csrfmiddlewaretoken': ['SzkStJ8PCm0Dw2v5cDUW6NEBAnUPcUo2kPK6JtTdAz1uqro3HmitDR0CFCgJbzp1'], 'phone': ['１１１１１'], 'password': ['111111']}>

            data = request.POST.dict()
           
            data.pop('csrfmiddlewaretoken')

            # 密码加密
            data['password'] = make_password(data['password'],None,'pbkdf2_sha256')


            # 头像上传
            myfile = request.FILES.get('pic_url')
            # print(myfile,type(myfile))   liyifeng02.jpg <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
            if myfile:
                # 调用函数进行头像上传
                data['pic_url'] = uploads(myfile)
            else:
                data['pic_url'] = '/static/pics/users.jpg'
            # 进行数据的添加
            ob = models.Users(**data)
            ob.save()
            return HttpResponse('<script>alert("添加成功!");location.href="'+reverse('myadmin_userindex')+'"</script>')
    except:
            return HttpResponse('<script>alert("添加失败!");location.href="'+reverse('myadmin_useradd')+'"</script>')


@permission_required('myadmin.edit_users',raise_exception = True)
# 后台用户修改
def useredit(request,uid):
    try:
        # 根据请求的id获取对象
        ob = models.Users.objects.get(id=uid)
        # 判断请求的方式
        if request.method == 'GET':
            context = {'userinfo':ob}
            return render(request,'myadmin/users/edit.html',context)
        elif request.method == 'POST':
            ob.username = request.POST.get('username')
            # 密码判断
            if request.POST.get('password'):
                # 如果修改了密码就执行下面的语句
                ob.password = make_password(request.POST['password'],None,'pbkdf2_sha256')
            ob.phone = request.POST.get('phone')
            ob.email = request.POST.get('email')
            ob.age = request.POST.get('age')
            ob.sex = request.POST.get('sex')
            # 判断是否更新了头像
            myfile = request.FILES.get('pic_url')
            if myfile:
                # 如果修改了头像，就要上传新的头像，并判断是否删除以前的头像
                # if ob.pic_url != '/static/pics/users.jpg':
                    # 删除原来上传的头像
                    # os.remove(BASE_DIR+ob.pic_url)

                # 将新上传的头像更新
                ob.pic_url = uploads(myfile)
            ob.save()
            return HttpResponse('<script>alert("更新成功！");location.href="'+reverse('myadmin_userindex')+'"</script>')
    except:
            return HttpResponse('<script>alert("更新失败！");location.href="'+reverse('myadmin_useredit')+'"</script>')


@permission_required('myadmin.del_users',raise_exception = True)
# 后台用户删除
def userdel(request,uid):
    # 根据id获取用户对象，修改状态,不做物理删除
    ob = models.Users.objects.get(id=uid)
    ob.status = 3
    ob.save()
    return HttpResponse('<script>alert("删除成功！");location.href="'+reverse('myadmin_userindex')+'"</script>')


